package service

import (
	"dks-goweb/model"
	"dks-goweb/utils"
	"encoding/json"
	"fmt"
	"strings"
)

// QueryCardStatus 查询卡片状态
func QueryCardStatus(cardNumber string) (model.CustomCardStateResponse, error) {
	// 构造请求的JSON参数  json.Marsha把对象序列化为JSON
	requestBody, err := json.Marshal(model.CardRequest{Card: cardNumber})
	if err != nil {
		return model.CustomCardStateResponse{}, err
	}

	// 使用工具类发送POST请求
	responseBody, err := utils.PostRequest("https://wx.88iot.net/iot/card/queryCardStatus", requestBody)
	if err != nil {
		return model.CustomCardStateResponse{}, err
	}

	// 解析响应数据
	var cardResponse model.CardStateResponse
	//json.Unmarshal把JSON反序列化为结构体
	err = json.Unmarshal(responseBody, &cardResponse)
	if err != nil {
		var str string = ""
		print(json.Unmarshal(responseBody, str))
		fmt.Printf("%d\n", str)
		return model.CustomCardStateResponse{}, err
	}

	// 创建自定义的返回结构体
	customResponse := model.CustomCardStateResponse{
		Msg:    cardResponse.Msg,
		Status: cardResponse.Data.Status,
	}

	return customResponse, nil
}

// QueryCardPackage 网亿查询流量包
func QueryCardPackage(cardNumber string) (model.CardPackageResponseBody, error) {

	// 将请求体序列化为JSON
	jsonBody, err := json.Marshal(model.CardRequest{Card: cardNumber})
	if err != nil {
		return model.CardPackageResponseBody{Msg: "序列化为JSON时出现错误:" + err.Error(), CardDealer: "未知"}, err

	}
	// 发送POST请求
	body, err := utils.PostRequest("https://wx.88iot.net/iot/card/v2/queryCardPackage", jsonBody)
	if err != nil {
		return model.CardPackageResponseBody{Msg: "发送POST请求时出现错误:" + err.Error(), CardDealer: "未知"}, err

	}

	// 解析响应体
	var responseBody model.CardPackageResponseBody
	err = json.Unmarshal(body, &responseBody)
	if err != nil {
		return model.CardPackageResponseBody{Msg: "解析响应体时出现错误:" + err.Error(), CardDealer: "未知"}, err

	}
	if responseBody.Msg == "success" {
		responseBody.CardDealer = "网亿"
	} else if strings.Contains(responseBody.Msg, "卡不存在") {
		responseBody.CardDealer = "未知"
	} else if strings.Contains(responseBody.Msg, "该卡目前暂无法使用") {
		responseBody.CardDealer = "网亿"
		responseBody.Status = "卡已被注销"
	} else if strings.Contains(responseBody.Msg, "请输入正确的卡号") {
		responseBody.CardDealer = "未知"
		responseBody.Status = "卡号不正确"
	}
	return responseBody, nil
}

// QueryCardStatusAndPackage查询卡片状态和全部流量包
func QueryCardStatusAndPackage(cardNumber string) (model.CardPackageResponseBody, error) {
	state, err := QueryCardStatus(cardNumber)
	if err != nil {

		return model.CardPackageResponseBody{}, err
	}

	packages, err := QueryCardPackage(cardNumber)
	if err != nil {

		return model.CardPackageResponseBody{}, err
	}

	if packages.Status == "" {
		packages.Status = state.Status

	}

	return packages, nil

}
